package com.huaxiafinance.management.util;


import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletResponse;
import java.io.*;


/**
 * Created by Administrator on 2017/5/26 0026.
 */

public class FtpUploadUtil
{

    private static final Logger log = Logger.getLogger(FtpUploadUtil.class);

    private static FTPClient ftp;

    private static final int BINARY_FILE_TYPE = FTP.BINARY_FILE_TYPE;

    private static final int ASCII_FILE_TYPE = FTP.ASCII_FILE_TYPE;

    /**
     * 服务器地址
     */
    private static final String server = PropertiesLoader.getProperty("ftp.server");

    /**
     * 用户名
     */
    private static final String username = PropertiesLoader.getProperty("ftp.username");

    /**
     * 密码
     */
    private static final String password = PropertiesLoader.getProperty("ftp.password");

    /**
     * 端口
     */
    private static final int port = Integer.parseInt(PropertiesLoader.getProperty("ftp.port"));

    /**
     * Description: 向FTP服务器上传文件
     *
     * @param path
     *            FTP服务器保存目录
     * @param filename
     *            上传到FTP服务器上的文件名
     * @param input
     *            输入流
     * @return 成功返回true，否则返回false
     */
    public static boolean uploadFile(String path, String filename, InputStream input)
    {
        boolean success = false;
        FTPClient ftp = new FTPClient();
        try
        {
            int reply;
            ftp.connect(server, port);// 连接FTP服务器
            // 如果采用默认端口，可以使用ftp.connect(url)的方式直接连接FTP服务器
            ftp.login(username, password);// 登录
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply))
            {
                ftp.disconnect();
                return success;
            }

            String[] spPath = path.split("/");

            for (int i = 0; i < spPath.length; i++ )
            {
                if (spPath[i] == null || spPath[i].trim().isEmpty())
                {
                    continue;
                }
                ftp.makeDirectory(spPath[i]);
                ftp.changeWorkingDirectory(spPath[i]);
            }

            ftp.enterLocalPassiveMode();
            success = ftp.storeFile(filename, input);

            ftp.logout();
        }
        catch (IOException e)
        {
            log.error("错误++++++" + e);
        }
        finally
        {
            if (ftp.isConnected())
            {
                try
                {
                    ftp.disconnect();
                }
                catch (IOException ioe)
                {
                    log.error("错误++++++" + ioe);
                }
            }
        }
        return success;
    }

    /**
     * Description: 从FTP服务器下载文件
     *
     * @param remotePath
     *            FTP服务器上的相对路径
     * @param fileName
     *            要下载的文件名
     * @return InputStream @Version. Jul , :: PM by 崔红保（cuihongbao@d-heaven.com）创建
     */
    public static InputStream downFile(String remotePath, String fileName,
                                       HttpServletResponse response)
    {
        boolean success = false;
        InputStream it = null;
        FTPClient ftp = new FTPClient();
        try
        {
            int reply;
            ftp.connect(server, port);
            // 如果采用默认端口，可以使用ftp.connect(url)的方式直接连接FTP服务器
            ftp.login(username, password);// 登录
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply))
            {
                ftp.disconnect();
                return null;
            }
            ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
            FTPFile[] fs = ftp.listFiles();
            for (FTPFile ff : fs)
            {
                if (ff.getName().equals(fileName))
                {
                    ftp.setBufferSize(524288);
                    ByteArrayOutputStream fos = new ByteArrayOutputStream();

                    // 一分期
                    ftp.enterLocalPassiveMode();
                    ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
                    success = ftp.retrieveFile(fileName, fos);

                    if (success != true)
                    {
                        ftp.disconnect();
                    }
                    it = new ByteArrayInputStream(fos.toByteArray());

                    response.setContentType("application/msword;charset=\"gbk\"");
                    response.addHeader("Content-Disposition",
                        "attachment;filename=" + new String(("端口资源情况统计报表.doc").getBytes("GB2312"),
                            "iso8859-1"));
                    try (OutputStream ous = new BufferedOutputStream(response.getOutputStream()))
                    {
                        // 文件拷贝
                        byte flush[] = new byte[1024];
                        int len = 0;
                        while (0 <= (len = it.read(flush)))
                        {
                            ous.write(flush, 0, len);
                        }
                        // 关闭流的注意 先打开的后关
                        it.close();
                        fos.close();
                    }
                    catch (IOException e)
                    {
                        log.error("错误++++++" + e);
                    }
                }
            }
            ftp.logout();
            success = true;
        }
        catch (IOException e)
        {
            log.error("错误++++++" + e);
        }
        finally
        {
            if (ftp.isConnected())
            {
                try
                {
                    ftp.disconnect();
                }
                catch (IOException ioe)
                {
                    log.error("错误++++++" + ioe);
                }
            }
        }
        return it;
    }

    /**
     * ftp进行分行读取ftp内容
     *
     * @param remotePath
     *            要下载的文件地址
     * @param fileName
     *            要下载的文件名
     * @return BufferedReader
     */
    public static BufferedReader readData(String remotePath, String fileName)
    {
        log.error("开始读取ftp文件内容====================" + remotePath + fileName);

        boolean success = false;

        FileInputStream inFile = null;
        InputStream in = null;
        BufferedReader br = null;

        FTPClient ftp = new FTPClient();
        ftp.setControlEncoding("gb18030");
        try
        {
            int reply;
            ftp.connect(server, port);

            // 如果采用默认端口，可以使用ftp.connect(url)的方式直接连接FTP服务器
            ftp.login(username, password);// 登录
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply))
            {
                log.info("ftp登入" + remotePath + fileName + "失败====================");
                ftp.disconnect();
                return null;
            }
            try
            {
                ftp.setControlEncoding("gb18030"); // 中文支持
                ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
                ftp.enterLocalPassiveMode();
                ftp.setBufferSize(524288);
                ftp.changeWorkingDirectory(remotePath);
                in = ftp.retrieveFileStream(fileName);
            }
            catch (FileNotFoundException e)
            {
                log.error("没有找到" + remotePath + fileName + "文件====================");
                return null;
            }
            catch (IOException e)
            {
                log.error(remotePath + fileName + "文件读取错误=========================");
                return null;
            }

            if (in != null)
            {
                br = new BufferedReader(new InputStreamReader(in, "utf-8"));
            }
            else
            {
                log.info(remotePath + fileName + "文件读取错误=========================");
                return null;
            }
            ftp.logout();
            success = true;
        }
        catch (IOException e)
        {
            log.error(remotePath + fileName + "文件读取错误=========================");
        }
        finally
        {
            if (ftp.isConnected())
            {
                try
                {
                    ftp.disconnect();
                }
                catch (IOException ioe)
                {
                    log.error("ftp关闭失败=========================");
                }
            }
        }
        log.info("结束读取ftp文件内容====================" + remotePath + fileName);
        return br;
    }
}